package com.sg.file.receive.provider.service;

import com.sg.file.common.conf.FileConfiguration;
import com.sg.file.manager.api.IFileInfoService;
import com.sg.file.receive.api.dto.ByteFileReceiveRequest;
import com.sg.file.receive.api.dto.FileCreateDTO;
import com.sg.file.receive.api.dto.FileReceiveResponse;
import com.sg.file.receive.provider.util.filereceive.AbstractFileReceive;
import com.sg.file.receive.api.IFileReceiveService;
import com.sg.file.manager.repository.pojo.FileInfo;
import com.sg.file.transform.api.ITransformService;
import com.sg.file.transform.api.dto.TransformReqeust;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 本地文件文件接收
 * Created by asus on 2018/7/9.
 */
@Service(value = "localFileReceive")
public class LocalFileReceiveService implements IFileReceiveService {

    @Autowired
    private AbstractFileReceive byteFileReceive;
    @Autowired
    private FileConfiguration fileConfiguration;
    @Autowired
    private IFileInfoService fileInfoService;
    @Autowired
    private ITransformService transformService;

    @Override
    public FileReceiveResponse receiveAndAdd(List<ByteFileReceiveRequest> byteFileReceiveRequests) {
        //接收更新
        FileReceiveResponse receiveResponse = receive(byteFileReceiveRequests);
        //文件入库
        fileInDB(receiveResponse.getSuccFiles());
        //文件插入转换队列
        fileInTransQueue(receiveResponse.getSuccFiles());

        return receiveResponse;
    }

    @Override
    public FileReceiveResponse receiveAndAdd(ByteFileReceiveRequest byteFileReceiveRequest) {
        List<ByteFileReceiveRequest> byteFileReceiveRequests = new ArrayList<>();
        byteFileReceiveRequests.add(byteFileReceiveRequest);
        return receiveAndAdd(byteFileReceiveRequests);
    }


    @Override
    public FileReceiveResponse receiveAndUpdate(ByteFileReceiveRequest byteFileReceiveRequest) {
        FileReceiveResponse fileReceiveResponse = null;
        //查询文件
        FileInfo fileInfo = fileInfoService.getById(byteFileReceiveRequest.getFileId());
        if(fileInfo==null){
            //如果没有此文件则直接返回
            fileReceiveResponse = new FileReceiveResponse();
            fileReceiveResponse.addFailFile(byteFileReceiveRequest.getFileName());
            fileReceiveResponse.setMessage("没有文件ID为:"+byteFileReceiveRequest.getFileId());
            return fileReceiveResponse;
        }
        //获取项目名称
        byteFileReceiveRequest.setProName(fileInfo.getProjectName());
        List<ByteFileReceiveRequest> byteFileReceiveRequests = new ArrayList<>();
        byteFileReceiveRequests.add(byteFileReceiveRequest);
        return receiveAndUpdate(byteFileReceiveRequests);
    }


    private FileReceiveResponse receiveAndUpdate(List<ByteFileReceiveRequest> byteFileReceiveRequests) {
        //TODO
        // 此处缺少文件回滚机制
        //接收更新
        FileReceiveResponse receiveResponse = receive(byteFileReceiveRequests);
        //文件入库
        fileInDB(receiveResponse.getSuccFiles());
        //文件插入转换队列
        fileInTransQueue(receiveResponse.getSuccFiles());
        return receiveResponse;
    }

    /**
     * 接收并保存获取更新文件信息
     * @param byteFileReceiveRequests
     * @return
     */
    private FileReceiveResponse receive(List<ByteFileReceiveRequest> byteFileReceiveRequests){
        //返回对象
        FileReceiveResponse fileReceiveResponse = new FileReceiveResponse();
        //成功写入文件集合
        List<FileCreateDTO> succList = new ArrayList<>();
        //写入失败文件名集合
        List<String> failList = new ArrayList<>();
        //文件接收并存储到物理磁盘
        for(ByteFileReceiveRequest byteFileReceiveRequest:byteFileReceiveRequests){
            FileCreateDTO fileCreateDTO = byteFileReceive.receive(byteFileReceiveRequest);
            if(fileCreateDTO==null){
                //如果为空则说明失败加入失败队列
                failList.add(byteFileReceiveRequest.getFileName());
            }
            //存储到物理磁盘成功加入成功队列
            succList.add(fileCreateDTO);
        }

        //响应
        fileReceiveResponse.setSuccFiles(succList);
        fileReceiveResponse.setFailFiles(failList);
        return fileReceiveResponse;
    }

    /**
     * 入库
     * @param succList
     */
    private void fileInDB(List<FileCreateDTO> succList){
        //判断是否入库
        if(fileConfiguration.isSaveInDB()) {
            List<FileInfo> fileInfos = new ArrayList<>();
            for (FileCreateDTO fileCreateDTO : succList) {
                fileInfos.add(toFileInfo(fileCreateDTO));
            }
            //进行入库操作
            if (succList != null && succList.size() > 0) {
                fileInfoService.saveAll(fileInfos);
            }
        }
    }

    /**
     * 转换
     * @param succList
     */
    private void fileInTransQueue(List<FileCreateDTO> succList){

        for(FileCreateDTO fileCreateDTO:succList){
            //自动转换默认格式
            boolean autoTransform = fileConfiguration.getAutoTransform(fileCreateDTO.getFileType());
            //自动转换缩略图
            boolean autoTransformThumbnail = fileConfiguration.getAutoTransformThumbnail(fileCreateDTO.getFileType());
            TransformReqeust transformReqeust = null;
            TransformReqeust transformThumbnailReqeust = null;
            if(autoTransform){
                //转换成TransformReqeust
                transformReqeust = TransformReqeust.toTransformRequest(fileCreateDTO,
                        fileConfiguration.getDefaultTransformSuffix(fileCreateDTO.getFileType()),
                        fileConfiguration.getPath().getBase(),
                        fileConfiguration.getDefaultTransformClass(fileCreateDTO.getFileType()));
            }
            //如果是默认还需要转换压缩图片，所以还需要创建一个转换请求
            if(autoTransformThumbnail){
                //转换成TransformReqeust
                transformThumbnailReqeust = TransformReqeust.toTransformRequest(fileCreateDTO,
                        fileConfiguration.getDefaultTransformThumbnailSuffix(fileCreateDTO.getFileType()),
                        fileConfiguration.getPath().getBase(),
                        fileConfiguration.getDefaultTransformThumbnailClass(fileCreateDTO.getFileType()));
            }

            //将转换任务添加到任务队列,进行异步转换
            transformService.doTransformAsyn(transformReqeust,transformThumbnailReqeust);
        }
    }

    /**
     * 将filecreatedto转换成pojo类进行入库操作
     * @param fileCreateDTO
     * @return
     */
    private FileInfo toFileInfo(FileCreateDTO fileCreateDTO){
        FileInfo fileInfo = new FileInfo();
        fileInfo.setProjectName(fileCreateDTO.getProjectName());
        fileInfo.setFileId(fileCreateDTO.getFileId());
        fileInfo.setFilePath(fileCreateDTO.getFilePath());
        fileInfo.setFileSize(fileCreateDTO.getFileSize());
        fileInfo.setFileSuffix(fileCreateDTO.getFileSuffix());
        fileInfo.setFileType(fileCreateDTO.getFileType());
        fileInfo.setInDate(fileCreateDTO.getInDate());
        fileInfo.setOriginalFileName(fileCreateDTO.getOriginalFileName());
        fileInfo.setSaveFileName(fileCreateDTO.getSaveFileName());
        return fileInfo;
    }

    /**
     * 从配置文件中获取转换类型和是否需要转换，
     */
    private ByteFileReceiveRequest setTranceInfo(ByteFileReceiveRequest byteFileReceiveRequest){
        List<FileConfiguration.TransformInfo> transformInfos = fileConfiguration.getTransformInfos();
        for(FileConfiguration.TransformInfo transformInfo:transformInfos){
            //判断是否需要转换并赋值
            if(transformInfo.getType().equals(byteFileReceiveRequest.getContentType())){
                byteFileReceiveRequest.setBeTransform(transformInfo.isAutoTransformEnable());
                byteFileReceiveRequest.setTransToType(transformInfo.getFormatType());
                break;
            }
        }
        return byteFileReceiveRequest;
    }
}
